package com.billionsfinance.hessian.core;

import com.billionsfinance.hessian.common.anno.HessianPath;
import com.billionsfinance.hessian.common.machine.MachineResource;
import com.billionsfinance.hessian.common.utils.ZkPathBuilder;
import com.caucho.hessian.client.HessianProxyFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.MalformedURLException;

/**
 * 远程方法调用
 *
 * @ ClassName: RemoteCall.java
 * @ Author: WeiHui-Z
 * @ Date: 2016/11/24 19:32
 * @ Version: v1.0.0
 */
public class RemoteCall {

	private final static Logger LOGGER = LoggerFactory.getLogger(RemoteCall.class);

	@SuppressWarnings("unchecked")
	public static <T> T getRemoteObject(Class<T> classType) {
		HessianPath hessianPath = classType.getAnnotation(HessianPath.class);

		String group = hessianPath.group();
		String edition = hessianPath.edition();
		String name = classType.getName();

		String buildPath = ZkPathBuilder.buildPath(group, name, edition);

		String resource = MachineResource.getInstance().getResource(buildPath);

		String[] split = resource.split(",");
		HessianProxyFactory factory = new HessianProxyFactory();
		factory.setConnectTimeout(Integer.parseInt(split[1]) * 1000);
		factory.setReadTimeout(Integer.parseInt(split[2]) * 1000);

		String url = split[0];
		LOGGER.info("当前hessian请求链接: {}", url);

		T object = null;
		try {
			object = (T) factory.create(classType, url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return object;
	}

}